package com.yotoodesign.dianba.fragment;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.WeiboParameters;
import com.weibo.sdk.android.api.AccountAPI;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.net.RequestListener;
import com.yotoodesign.core.util.LoadDataAsynTask;
import com.yotoodesign.core.util.LoadImageAsynTask;
import com.yotoodesign.core.util.NetUtil;
import com.yotoodesign.dianba.R;
import com.yotoodesign.dianba.adapter.TagAdapter;
import com.yotoodesign.dianba.app.GlobalApplication;
import com.yotoodesign.dianba.bean.MicroBlogUser;
import com.yotoodesign.dianba.bean.Tag;
import com.yotoodesign.dianba.util.AccessTokenKeeper;
import com.yotoodesign.dianba.util.JSONUtil;
import com.yotoodesign.dianba.util.WeiboConstant;


public class UserCenterFragment extends BaseFragment{

	TagAdapter tagAdapter;
	GridView gvTags;
	
	public TextView tvScreenName;
	public TextView tvLocation;
	public RelativeLayout loginLayout;
	public RelativeLayout userLayout;
	public ImageView ivAvatar;
	
	private Weibo mWeibo;
	public static Oauth2AccessToken accessToken;
	
	final Handler loginHandler = new Handler();
	
	
	final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateUserInfo();
        }
    };
    
    private void updateUserInfo(){
    	MicroBlogUser user = GlobalApplication.getInstance().currentUser;
    	tvScreenName.setText(user.screenName);
    	tvLocation.setText(user.location);
    	loginLayout.setVisibility(View.GONE);
    	userLayout.setVisibility(View.VISIBLE);
    	
    	LoadImageAsynTask.defaultImg = R.drawable.man;
    	LoadImageAsynTask.loadFromUrl(ivAvatar, user.profileImageUrl, WeiboConstant.EXTERNAL_DIR_CACHE);
    	GlobalApplication.getInstance().logined = true;
    	
    }
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view =  inflater.inflate(R.layout.user_center, container,false);
		final TextView mainTitle = (TextView)view.findViewById(R.id.mainTitle);
		mainTitle.setText(R.string.user_center);
		ImageButton commonBack = (ImageButton)view.findViewById(R.id.commonBack);
		commonBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				GlobalApplication.getMainActivity().goHome();
			}
		});
		
		final Button btnEdit = (Button)view.findViewById(R.id.btnEdit);
		btnEdit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(btnEdit.getText().toString().equals(getString(R.string.edit))){
					btnEdit.setText(getString(R.string.editOk));
					btnEdit.setBackgroundResource(R.drawable.green_button);
					//设置标签为可编辑状态
					tagAdapter.setEditing(true);
					tagAdapter.notifyDataSetChanged();
					
				}else{
					btnEdit.setText(getString(R.string.edit));
					btnEdit.setBackgroundResource(R.drawable.gray_button);
					//提交编辑结果
					tagAdapter.setEditing(false);
					tagAdapter.notifyDataSetChanged();
				}
			}
		});
		
		Button btnLogin = (Button)view.findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!new NetUtil(getActivity()).isConnected()){
					Toast.makeText(getActivity(), "网络似乎不通哦！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				mWeibo = Weibo.getInstance(WeiboConstant.APP_KEY, WeiboConstant.REDIRECT_URL);
				mWeibo.authorize(getActivity(), new AuthDialogListener());
				
				WeiboParameters wp = new WeiboParameters();
			}
		});
		
		//添加标签
		Button btnAddTag = (Button)view.findViewById(R.id.btnAddTag);
		btnAddTag.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showTagInput();
			}
		});
		
		Button btnSearchLike = (Button)view.findViewById(R.id.btnSearchLike);
		btnSearchLike.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
			}
		});
		
		tvScreenName = (TextView)view.findViewById(R.id.tvScreenName);
		tvLocation = (TextView)view.findViewById(R.id.tvLocation);
		loginLayout = (RelativeLayout)view.findViewById(R.id.loginLayout);
		userLayout = (RelativeLayout)view.findViewById(R.id.userLayout);
		ivAvatar = (ImageView)view.findViewById(R.id.ivAvatar);
		
		//我的标签
		ArrayList<Tag> tags = GlobalApplication.getInstance().loadMyTags();
		gvTags = (GridView)view.findViewById(R.id.gvTags);
		tagAdapter = new TagAdapter(getActivity());
		tagAdapter.setTags(tags);
		gvTags.setAdapter(tagAdapter);
		return view;
	}

	@Override
	public void updateListView() {
		// TODO Auto-generated method stub
		
	}
	
	public void showTagInput() {
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setTitle(getString(R.string.add_tag));
		final LayoutInflater inflater = LayoutInflater.from(getActivity());
		View v = inflater.inflate(R.layout.edit_tag, null);
		final EditText etTag = (EditText)v.findViewById(R.id.etTag);

		builder.setView(v);
		builder.setNegativeButton(R.string.cancel, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).setPositiveButton(R.string.add_tag, new OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String text = etTag.getText().toString();
				if(text.equals("")){
					Toast.makeText(getActivity(), "请输入标签！", Toast.LENGTH_SHORT).show();
				}else{
					GlobalApplication.getInstance().saveTag(new Tag(text));
					tagAdapter.getTags().add(new Tag(text));
					dialog.dismiss();
				}
			}
			
		});
		
		builder.create().show();
	}
	
	public void updateStatus(String text){
		StatusesAPI api = new StatusesAPI(UserCenterFragment.accessToken);
		api.update(text, "0", "0", new RequestListener(){

			@Override
			public void onComplete(String arg0) {
				Looper.prepare();
				Toast.makeText(getActivity(), "分享点歌单成功", Toast.LENGTH_SHORT).show();
				GlobalApplication.hideProgress();
				Looper.loop();
			}

			@Override
			public void onError(WeiboException arg0) {
				Looper.prepare();
				Toast.makeText(getActivity(), "分享点歌单失败"+arg0.getMessage(), Toast.LENGTH_SHORT).show();
				GlobalApplication.hideProgress();
				Looper.loop();
				
			}

			@Override
			public void onIOException(IOException arg0) {
				Looper.prepare();
				Toast.makeText(getActivity(), "分享点歌单失败"+arg0.getMessage(), Toast.LENGTH_SHORT).show();
				GlobalApplication.hideProgress();
				Looper.loop();
			}
			
		});
	}
	
	class AuthDialogListener implements WeiboAuthListener {
		
        @Override
        public void onComplete(Bundle values) {
            String token = values.getString("access_token");
            String expires_in = values.getString("expires_in");
            UserCenterFragment.accessToken = new Oauth2AccessToken(token, expires_in);
            if (UserCenterFragment.accessToken.isSessionValid()) {
                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
                        .format(new java.util.Date(UserCenterFragment.accessToken
                                .getExpiresTime()));
                Log.i(WeiboConstant.APP,"认证成功: \r\n access_token: " + token + "\r\n"
                        + "expires_in: " + expires_in + "\r\n有效期：" + date);
                
                AccessTokenKeeper.keepAccessToken(getActivity(),
                        accessToken);
                Toast.makeText(getActivity(), "认证成功", Toast.LENGTH_SHORT)
                        .show();
                
                //查询关注微博
                
                AccountAPI actApi = new AccountAPI(UserCenterFragment.accessToken);
                actApi.getUid(new RequestListener(){

					@Override
					public void onComplete(String json) {
						
						String uid = JSONUtil.parseUID(json);
						UsersAPI usersApi = new UsersAPI(UserCenterFragment.accessToken);
						usersApi.show(Long.valueOf(uid), new RequestListener(){

							@Override
							public void onComplete(String json) {
								MicroBlogUser user = JSONUtil.parseUser(json);
								GlobalApplication.getInstance().currentUser = user;
								
								Thread t = new Thread() {
						            public void run() {
						            	loginHandler.post(mUpdateResults); 
						            }
						        };
						        t.start();
							}

							@Override
							public void onError(WeiboException arg0) {
								// TODO Auto-generated method stub
								Log.i(WeiboConstant.APP,"认证失败："+arg0.getMessage());
							}

							@Override
							public void onIOException(IOException arg0) {
								// TODO Auto-generated method stub
								
							}
							
						});
					}

					@Override
					public void onError(WeiboException arg0) {
						
					}

					@Override
					public void onIOException(IOException arg0) {
						
					}
                	
                });
                
            }
        }

        @Override
        public void onError(WeiboDialogError e) {
            Toast.makeText(getActivity().getApplicationContext(),
                    "Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getActivity().getApplicationContext(), "Auth cancel",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(getActivity().getApplicationContext(),
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
        
    }
	
	/*
	 * 保存点歌单数据
	 */
	private String getParams(){
		String id = "zhuzijia@gmail.com";
		String name = "朱梓嘉的点歌单";
		String desc  = "测试用的哦";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
		String createDate = sdf.format(new Date());
		String songs_singers = "2222,老爸,00912,朱传明::333,老妈,3434,谢晓霞";
		
		String url = "";
		
		url += "id="+id;
		url += "&name="+name;
		url += "&desc="+desc;
		url += "&createDate="+createDate;
		url += "&songs_singers="+songs_singers;
		return url;
	}

}
